package java10;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class JdbcTest04 {
    public static void main(String[] args){
        JdbcTest04 jdbc = new JdbcTest04();
        List<Student> list = jdbc.findAll();
        System.out.println(list);
    }
    public List<Student> findAll(){
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        List<Student> list = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            String url = "jdbc:mysql://localhost:3306/db1";
            String username = "root";
            String password = "root";
            conn = DriverManager.getConnection(url,username,password);
            stmt = conn.createStatement();
            String sql = "select * from student";
            rs= stmt.executeQuery(sql);
            Student stu = null;
            list = new ArrayList<>();
            while(rs.next()){
                int id = rs.getInt("id");
                String name = rs.getString("NAME");
                int age = rs.getInt("age");
                String sex = rs.getString("sex");
                String address = rs.getString("address");
                int math = rs.getInt("math");
                int english = rs.getInt("english");
                stu = new Student();
                stu.setId(id);
                stu.setName(name);
                stu.setAge(age);
                stu.setSex(sex);
                stu.setAddress(address);
                stu.setMath(math);
                stu.setEnglish(english);
                list.add(stu);
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            if(rs != null){
                try {
                    rs.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if(stmt != null){
                try {
                    stmt.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if(conn != null){
                try {
                    conn.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
        return list;
    }
}
